﻿
using System ;

using MskEdit.Dxf.Model ;
using MskEdit.Sdk ;


namespace MskEdit.Dxf.Backend
{

    public static class DxfDoubleReader
    {
        public static double? TryParse( string valueStr, int lineNo, double? fallbackValue ) {
                
            double? value = SdkValueParser.TryParseToDouble( valueStr, null ) ;
            if ( ! value.HasValue ) {
                SdkDiagnostics.TraceWarning( "Could not parse Double value string.", lineNo ) ;
                return fallbackValue ;
            }
            
            return value ;
        }


        public static double? TryRead( string codeStr, string[] allLines, ref int lineNo, double? fallbackValue ) {
        
            int internalLineNo = lineNo ;

            string valueStr = DxfLineReader.TryRead( codeStr, allLines, ref internalLineNo, null ) ;
            if ( valueStr == null )
                return fallbackValue ;
            
            double? value = TryParse( valueStr, internalLineNo, null ) ;
            if ( ! value.HasValue )
                return fallbackValue ;
            
            lineNo = internalLineNo ;
            
            return value ;
        }
        
        
        public static double? TryReadAfterCode( string[] allLines, ref int lineNo, double? fallbackValue )
        {
            int internalLineNo = lineNo ;
            
            string valueStr = DxfLineReader.TryRead( allLines, ref internalLineNo, null ) ;
            if ( valueStr == null ) {
                SdkDiagnostics.TraceWarning( "Could not read Double value string.", internalLineNo ) ;
                return fallbackValue ;
            }
                 
            double? value = TryParse( valueStr, internalLineNo, null ) ;
            if ( ! value.HasValue )
                return fallbackValue ;
            
            lineNo = internalLineNo ;
            
            return value ;
        }


        public static double? TryRead( string[] allLines, ref int lineNo, double? fallbackValue ) {
        
            int internalLineNo = lineNo ;
            
            DxfCode dxfCode = DxfCodeReader.TryRead( allLines, ref internalLineNo, null ) ;
            if ( dxfCode == null )
                return fallbackValue ;
            
            if ( ! dxfCode.HasDoubleCode )
                return fallbackValue ;
            
            double? value = TryReadAfterCode( allLines, ref internalLineNo, null ) ;
            if ( ! value.HasValue )
                return fallbackValue ;
                
            lineNo = internalLineNo ;
            
            return value ;
        }
        
    }
}
